package com.simplenix.nicasio.admin.init;

import com.simplenix.nicasio.admin.eb.User;
import com.simplenix.nicasio.misc.AppException;
import com.simplenix.nicasio.persistence.HibernateUtil;
import com.simplenix.nicasio.sys.InitTask;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

/**
 *
 * @author fronald
 */
public class InitAdmin implements InitTask {

	public void doInit() throws AppException {
		Transaction t = HibernateUtil.getCurrentSession().beginTransaction();
		try {
			Criteria c = HibernateUtil.getCurrentSession().createCriteria(User.class);
			c.add(Restrictions.eq("login", "admin"));
			List<User> users = c.list();
			if (users != null && users.size() < 1) {
				User admin = new User();
				admin.setEmail("admin@admin.com.br");
				admin.setLogin("admin");
				admin.setName("Admin");
				admin.setPassword(User.encriptPassword("admin"));
				HibernateUtil.getCurrentSession().save(admin);
			}
			t.commit();
		} catch (Exception e) {
			t.rollback();
			throw new AppException(e);
		}
	}

	public String getDescription() {
		return "Init Admin module.";
	}

}
